/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：
* CreateTime：2020-08-21 09:46:55
* Version：1.0
* Modify Recorder：
*************************************************/

using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class ChatScrollView : MonoBehaviour
{
    public GameObject bubbleBoxPrefab;
    public Transform content;
    
    private ScrollRect scrollRect;

    private void Start()
    {
        scrollRect = transform.GetComponent<ScrollRect>();
    }

    public void AddBubbleBox(string message)
    {
        string[] strs = message.Split('|');
        string name = strs[0]; 
        string msg = strs[1];
        GameObject newBox = Instantiate(bubbleBoxPrefab, content);
        Text nameText = newBox.transform.Find("Name").GetComponent<Text>();
        Text msgText = newBox.transform.Find("BubbleBox/Text").GetComponent<Text>();
        nameText.text = name;
        
        if (msg.Length > 25)
        {
             StringBuilder strBuilder = new StringBuilder();
             int curNum = 0;
             for (int i = 0; i < msg.Length; i++)
             {
                 strBuilder.Append(msg[i]);
                 curNum++;
                 if (curNum >= 25)
                 {
                     strBuilder.Append("\n");
                     curNum = 0;
                 }
             }

             msg = strBuilder.ToString();
        }

        msgText.text = msg;
        float height = ((RectTransform)newBox.transform).sizeDelta.y + 15;
        ((RectTransform)newBox.transform).sizeDelta = new Vector2(((RectTransform)newBox.transform).sizeDelta.x,height);
        Invoke("MoveToDown", 0.1f);
    }

    private void MoveToDown()
    {
        scrollRect.verticalNormalizedPosition = 0;
    }
}
